package godb

import (
	"errors"
	"fmt"
	"github.com/spf13/cast"
	"github.com/xwb1989/sqlparser"
	"regexp"
)

var reg = regexp.MustCompile(":v\\d")

type selectSQL struct {
	selectColumns string
	table         string
	where         string
	groupBy       string
	having        string
	orderBy       string
	limitStart    int64
	limitLen      int64
}

// 解析mysql select语句
func mysqlSelectSQLParser(sql string) (selectSQL, error) {
	ret := selectSQL{}
	stmt, err := sqlparser.Parse(sql)
	if err != nil {
		return ret, fmt.Errorf("sql语句解析错误:%w", err)
	}
	switch stmt := stmt.(type) {
	case *sqlparser.Select:
		buf := sqlparser.NewTrackedBuffer(nil)
		stmt.SelectExprs.Format(buf)
		ret.selectColumns = buf.String()
		buf.Reset()
		stmt.From.Format(buf)
		ret.table = buf.String()
		buf.Reset()
		where := stmt.Where
		if where != nil {
			stmt.Where.Format(buf)
			ret.where = buf.String()
			if ret.where != "" {
				ret.where = regexp.MustCompile("(\\:v\\d+)").ReplaceAllString(ret.where, "?")
			}
			buf.Reset()
		}
		stmt.GroupBy.Format(buf)
		ret.groupBy = buf.String()
		buf.Reset()
		having := stmt.Having
		if having != nil {
			stmt.Having.Format(buf)
			ret.having = buf.String()
			buf.Reset()
		}
		stmt.OrderBy.Format(buf)
		ret.orderBy = buf.String()
		buf.Reset()
		limit := stmt.Limit
		if limit != nil {
			limit.Offset.Format(buf)
			ret.limitStart = cast.ToInt64(buf.String())
			buf.Reset()
			limit.Rowcount.Format(buf)
			ret.limitLen = cast.ToInt64(buf.String())
		}
		ret.table = reg.ReplaceAllString(ret.table, "?")
		ret.where = reg.ReplaceAllString(ret.where, "?")
		ret.having = reg.ReplaceAllString(ret.having, "?")
		return ret, nil
	default:
		return ret, errors.New("只支持select语句")
	}
}
